import pymysql
import os,time
import platform
from goods_feedback.config.setting import *
from goods_feedback.public.getlogging import Logger

filename=os.path.basename(__file__)   #获取对应路径下的文件名称
logging=Logger(filename).getlog()

class requestSQL():

    def __init__(self):
        self.conn=pymysql.connect(host=ip,
                        port=int(port),
                        user=user,
                        passwd=password,
                        db=database,
                        charset='utf8')
        self.cursor=self.conn.cursor()

    def sql_exe(self,sql):
        return self.cursor.execute(sql)

    def insert(self,tbname,field,values):
        insql="insert into %s(%s) values(%s)" %(tbname,field,values)
        return self.execute(insql)

    def select(self,tbname,field='*',where=''):
        if where:
            where=' where '+where
        selsql="select %s from %s %s" %(field,tbname,where)
        return self.execute(selsql)

    def update(self,tbname,where,keyvalues):
        setvalue=''
        for k,v in keyvalues.items():
            setvalue +='%s="%s"' %(k,v)
        if where:
            where=' where '+where
        upsql="update %s set %s %s" %(tbname,setvalue[:-1],where)
        return self.execute(ipsql)

    def delete(self,tbname,where):
        if where:
            where=' where '+where
        desql="delete from %s %s" %(tbname,where)
        return self.execute(desql)

    #execute
    def execute(self,sql):
        try:
            if sql.find('select')!=-1:
                self.cursor.execute(sql)
                return self.cursor.fetchall()
            elif sql.find('insert')!=-1 or sql.find('update') or sql.find('delete')!=-1:
                self.cursor.execute(sql)
                self.conn.commit()
                return True
            else:
                return False
        except Exception as e:
            print(str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))+'--'+str(e))
            return False

    #del
    def __del__(self):
        self.cursor.close()
        self.conn.close()

    def execute_selcet(self,sql:str,fetch:str)->list:
        '''

        :param sql: 查询语句
        :param fetch: 返回列表
        :return:
        '''
        self.cursor.execute(sql)
        if fetch=='fetchall':
            return self.cursor.fetchall()
        elif fetch=='fetchone':
            return self.cursor.fetchone()
        elif fetch=='fetchmany':
            return self.cursor.fetchmany()
        else:
            return None

if __name__=='__main__':
    requestsql=requestSQL()
    re = requestsql.execute_select("select * from ", 'fetchall')
    print(re)